﻿//作者: 小k
 var pickerpath = "";
 var defaults = {
     id: '',                   //对象ID
     title: '选择对象',        //标题
     height: '100%',           //高度
     width: '100%',            //宽度
     text: '',                 //已选文本
     value: '',                //已选值
     ismultiple: true,         //是否多选
     navindex: [],             //对应显示导航菜单的索引数组
     path: pickerpath,         //路径(如果插件路径非一般根目录,要增加路径地址.)
     parentid: '',             //父窗口id
     count:0,                  //数量
     content: '',              //内容
     url:'index.html',
     onselected: function (callback) { }, //当在picker选完对象后执行
     pickergird: {
         fieldtext: "attr1",
         fieldvalue: "itemid"
     }
 };
//对象级别定义
(function ($) {
    $.fn.pickerbox = function (options) {
        var opts = $.extend({}, defaults, options);
        var html = '';
        var tagName = $(this).attr("tagName");
        this.each(function () {
            opts.id = f.getBoxId($(this)); //修正为获取id
            
            var box = $(this);
            if (tagName == 'INPUT') {                  //如果是input
                box.after("<input id='" + opts.id + "_value'" + " type='hidden'></input>");
                box.attr("readonly", "readonly");
                box.css({ color: "grey" });
                setPickerLink(opts, "INPUT");
                bindPickerBtn(opts);
                return;
            }
            box.attr("multiple", "multiple");       //设置select元素多选模式
            html = "<div class='pickerbox-panel' style='display: block; width:" + opts.width + "'>";
            html += "<div class='pickerbox-panel-header'>";
            html += "<div class='pickerbox-panel-title pickerbox-panel-with-icon'>";
            html += "已选择:<span id='" + opts.id + "_count' style='font-weight:bold;color:Red'>0</span>条记录";
            html += "</div>";
            html += "<div class='pickerbox-panel-icon pickerbox-icon-edit'></div>";
            html += "</div>";

            html += "<div class='pickerbox-datagrid-wrap pickerbox-panel-body' style='padding:2px;'>";
            html += "<div class='pickerbox-datagrid-toolbar'>";
            html += "<a href='javascript:void(0)' style='float: left;'class='pickerbox-l-btn pickerbox-l-btn-plain' id='" + opts.id + "_title'><span class='pickerbox-l-btn-left'><span class='pickerbox-l-btn-text pickerbox-icon-add' style='padding-left: 20px;'>" + opts.title + "</span></span></a>";

            html += "<div class='pickerbox-datagrid-btn-separator'></div>";
            html += "<a href='javascript:void(0)' style='float: left;' class='pickerbox-l-btn pickerbox-l-btn-plain' id='" + opts.id + "_del'><span class='pickerbox-l-btn-left'><span class='pickerbox-l-btn-text pickerbox-icon-remove' style='padding-left:20px;'>删除</span></span></a>";

            html += "<div class='pickerbox-datagrid-btn-separator'></div>";
            html += "<a href='javascript:void(0)' style='float: left;' class='pickerbox-l-btn pickerbox-l-btn-plain' id='" + opts.id + "_clear'><span class='pickerbox-l-btn-left'><span class='pickerbox-l-btn-text pickerbox-icon-reload' style='padding-left:20px;'>清空</span></span></a>";
            html += "</div>";

            html += "<div style='padding: 5px;' class='pickerbox-datagrid-view' id='" + opts.id + "_body'>";
            html += "</div>";
            html += "</div>";

            html += "<input id='" + opts.id + "_value" + "' type='hidden'></input>";  //隐藏数据
            html += " </div>";
            $("#" + opts.id).replaceWith(html);
            $("#" + opts.id + "_body").html(box);
            box.css({ "width":"100%", "height": opts.height });
            f.build(opts);
            bindEvent(opts);
        });
    };

    //设置内容
    $.fn.pickerbox.setContent = function (p) {
        var o = $("#" + p.id);
        if (o.attr("tagName") == "INPUT")
            o.val(p.content);
        else
            o.html(p.content);
        $("#" + p.id + "_count").text(p.count);
        $("#" + p.id + "_value").val(p.value);
    };

    //函数对象
    var f = {
        //获得pickerboxId
        getBoxId: function (obj) {
            var id = obj.attr("id");
            if (id == undefined || id == '') {
                var newid = new Date().getTime();
                obj.attr("id", newid);
                return newid;
            } else {
                return id;
            }
        },
        //获得pickerbox按钮Id
        getBoxBtnId: function (obj) {
            var id = $(obj).attr("id").split('_')[0];
            if (id != '') {
                return id;
            }
            else {
                throw Error("对象错误.");
            }

        },
        //建立标准pickerbox
        build: function (p) {
            try {
                if (p.value.split(',').length != p.text.split(',').length) {
                    throw new Error("错误:元素的id为" + p.id + '值不匹配.');
                }
            } catch (e) {
                alert(e.message);
            }

            if (p.value == '' || p.text == '') {
                p.count = 0;
                p.content = '';
                p.value = '';
                $.fn.pickerbox.setContent(p); return;
                // $.fn.pickerbox.setContent(p.id, '', 0, ""); return;
            }
            var txt = p.text.split(",");
            var val = p.value.split(",");
            var html = '';
            var count = 0;

            for (var i = 0; i < val.length; i++) {
                html += "<option value='" + val[i] + "'>" + txt[i] + "</option>";
                count++;
            }
            $("#" + p.id + "_count").text(count);
            $("#" + p.id).html(html);

            if (p.value.substr(p.value.length - 1, 1) == ',')//如果最后一个字符有,号
            {
                $("#" + p.id + "_value").val(p.value);
            }
            else
                $("#" + p.id + "_value").val(p.value + ",");
        }
    };

    //绑定事件 
    function bindEvent(p) {
        //删除
        $("#" + p.id + "_del").unbind("click").bind("click", function () {
            var id = f.getBoxBtnId($(this));
            $("#" + id + " > option:selected").each(function () {
                var arrlist = $("#" + id + "_value").val().split(",");
                var index = $(this).index();
                for (var i = 0; i < arrlist.length; i++) {
                    if (arrlist[i] == $(this).attr("value")) {
                        updateValue(id + "_value", arrlist[i]);
                        $("#" + id + " option[value='" + $(this).attr("value") + "']").remove();
                        var obj = $("#" + id);
                        if (obj.children().length > index) {
                            obj.get(0).selectedIndex = index;
                        }
                        else {
                            obj.get(0).selectedIndex = index - 1;
                        }
                        return;
                    }
                }
            });
            setCount(id);
        });
        //清空
        $("#" + p.id + "_clear").unbind("click").bind("click", function () {
            var id = f.getBoxBtnId($(this));
            $("#" + id + "_value").val("");
            $("#" + id).html("");
            $("#" + id + "_count").text("0");
        });
        setPickerLink(p);
        bindPickerBtn(p);
    }

    //绑定传递值按钮(此处有待优化)
    function bindPickerBtn(p) {
        top.jQuery("#temppickerbtn").unbind("click").bind("click", function () {
            $("#pickerinnerbtn").click();
            var pid = $("#temppickerbtn").attr("pickerboxid") == undefined ? top.$("#temppickerbtn").attr("pickerboxid") : $("#temppickerbtn").attr("pickerboxid");
            var pickerbox = $.pickerbox;
            //callback
            var callbackobj ={
                    id: pid,
                    value: pickerbox.getValueById(pid),
                    text: pickerbox.getTextById(pid)
                };
            p.onselected(
                 callbackobj
            );
        });
    }

    //设置picker连接
    function setPickerLink(p, tag) {
        var url = p.path + p.url+"?d=" + new Date().getTime();
        url += "&parentid=" + p.parentid;
        url += (p.ismultiple == true ? "&ismultiple=true" : "&ismultiple=false");
        var index = p.navindex == "" ? "false" : p.navindex;
        url += "&navindex=" +index + "&pickerbox=" + p.id;
        url += "&fieldtext=" + p.pickergird.fieldtext + "&fieldvalue=" + p.pickergird.fieldvalue;
        var target = (tag == "INPUT" ? p.id : p.id + "_title");
        if (tag == 'INPUT') {
            url += "&tagname=input";
        }

        $("#" + target).unbind("click").bind("click", function () {
            var id = f.getBoxBtnId($(this));
            var pickerwidth = 790;
            var isIe = ! -[1, ];
            if (isIe) {
                pickerwidth = pickerwidth - 12;
            }
            top.asyncbox.open({
                url: url,
                id: "AsyncBox",
                width: pickerwidth,
                height: 514,
                title: "选择器"
            });
            top.jQuery("#temppickervalue").val(jQuery.pickerbox.getValueById(id));
            top.jQuery("#temppickertext").val(jQuery.pickerbox.getContentById(id));
            top.jQuery("#temppickercount").val(jQuery.pickerbox.getCountById(id));
        });
    }
    
    //更新选择值
    function updateValue(valueid, newvalue) {
        var re = new RegExp(newvalue + ",", "g");
        var str = $("#" + valueid).val();
        var newstart = str.replace(re, "");
        $("#" + valueid).val(newstart);
    }

    //设置记录数量
    function setCount(id) {
        var count = $("#" + id + "_value").val().split(",").length - 1;
        $("#" + id + "_count").text(count);
    }

})(jQuery);

//命名空间定义
jQuery.pickerbox = {
    //获得已选数量
    getCountById: function (id) {
        return jQuery("#" + id + "_count").text();
    },
    //获得Html内容
    getContentById: function (id) {
        return jQuery("#" + id).html();
    },
    //获取值
    getValueById: function (id) {
        var value = jQuery("#" + id + "_value").val();
        if (value.indexOf(',') >= 0) {
            return value.substr(0, value.length - 1);
        }
        else {
            return value;
        }
    },
    //获取已选的文本
    getTextById: function (id) {
        var text = '';
        var obj = $("#" + id);
        if(obj.attr("tagName").toUpperCase()=="INPUT") {
            return obj.val();
        }
        else {
            jQuery("#" + id + "> option").each(function() {
                if (jQuery(this).text() != '')
                    text += jQuery(this).text() + ",";
            });
            return text.substr(0, text.length - 1);
        }
    }
};

jQuery(window).ready(function () {
    //判断这个页面是否被iframe引用 或者还没添加中间传值元素
    if (location.href == top.location.href || $("a[class='temppicker']").length == 0) {
        jQuery("body").append("<input id='pickerinnerbtn' type='hidden' value='pickerinnerbtn'></input>");
        jQuery("#pickerinnerbtn").click(function () {
            var pid = top.jQuery("#temppickerid").val();
            var p = {
                id: pid,
                count: top.jQuery("#temppickercount").val(),
                text: top.jQuery("#temppickertext").val(),
                value: top.jQuery("#temppickervalue").val(),
                content: top.jQuery("#temppickertext").val()
            };
            jQuery("#" + pid).pickerbox.setContent(p);
        });
        //写入中间传值使用的元素
        var html = "<input id='temppickertext' class='temppicker' type='hidden' value='temppickertext'/><input  id='temppickervalue' class='temppicker' value='temppickervalue' type='hidden' /><input id='temppickercount' class='temppicker' type='hidden' value='temppickercount'/><input id='temppickerbtn' class='temppicker' type='hidden' value='temppickerbtn' /><input type='hidden' class='temppicker' id='temppickerid' value='temppickerid'/>";
        top.jQuery("body").after(html);
    }
});
 
